﻿//-----------------------------------------------------------------------
// <copyright file="ShortcutInfo.cs" author="Lennart">
//     License: MIT
// </copyright>
//-----------------------------------------------------------------------
namespace UtilityMethods {
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using Shell32;

    /// <summary>
    /// Provides functions to retreive information from shortcuts.
    /// </summary>
    public static class ShortcutInfo {
        /// <summary>
        /// Returns the filename that a shortcut refers to.
        /// </summary>
        /// <param name="shortcut">The shortcut to check.</param>
        /// <returns>The filename as ShellLinkObject or null if the filename couldn't be resolved.</returns>
        public static ShellLinkObject GetShortcutTarget(string shortcut) {
            Shell shellHandler = new Shell();
            Shell32.Folder folder = shellHandler.NameSpace(Path.GetDirectoryName(shortcut));
            FolderItem folderItem = folder.ParseName(Path.GetFileName(shortcut));
            if (folderItem != null) {
                ShellLinkObject shortcutTarget = (Shell32.ShellLinkObject)folderItem.GetLink;
                return shortcutTarget;
            }

            // TODO Check method calls for null
            return null;
        }

        /// <summary>
        /// Gets the file description of a given file.
        /// </summary>
        /// <param name="targetFile">The filename to check.</param>
        /// <param name="targetDirectory">The directory the file is in.</param>
        /// <param name="returnFilnameIfEmpty">If the file has no description, whether to return the file name instead.</param>
        /// <returns>Either the description of the file, the filename or an empty string.</returns>
        public static string GetFileDescription(string targetFile, string targetDirectory, bool returnFilnameIfEmpty) {
            FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(targetDirectory + "\\" + targetFile);
            if (fileInfo.FileDescription != null) {
                return fileInfo.FileDescription;
            }
            else {
                if (returnFilnameIfEmpty) {
                    return targetFile;
                }
                else {
                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// Returns the icon of a file.
        /// </summary>
        /// <param name="pathToFile">The file to extract from.</param>
        /// <returns>The extracted icon.</returns>
        public static Icon GetIcon(string pathToFile) {
            Icon fileIcon = Icon.ExtractAssociatedIcon(pathToFile);

            return fileIcon;
        }
    }
}
